package redis

import (
	"context"
	"github.com/go-redis/redis/v8"
	"github.com/siddontang/go-log/log"
	"time"
)

var client *redis.Client
var ctx = context.Background()

type RedisConfig struct {
	Host     string `yaml:"host"`
	Password string `yaml:"password"`
	Db       int    `yaml:"db"`       // Redis库
	PoolSize int    `yaml:"poolSize"` // Redis连接池大小
}

func CreatePool(config *RedisConfig) {
	client = redis.NewClient(&redis.Options{
		Addr:         config.Host,
		Password:     config.Password,
		DB:           config.Db,
		PoolSize:     config.PoolSize,
		IdleTimeout:  15 * time.Second,
		MinIdleConns: 1,
	})
}

func Get(key string) string {
	r, err := client.Get(ctx, key).Result()
	if err != nil {
		log.Println(err.Error())
		return ""
	}
	return r
}

func HGet(key string, filed string) string {
	r, err := client.HGet(ctx, key, filed).Result()
	if err != nil {
		log.Println(err.Error())
		return ""
	}
	return r
}

func HGetAll(key string) map[string]string {
	r, err := client.HGetAll(ctx, key).Result()
	if err != nil {
		log.Println(err.Error())
		return nil
	}
	return r
}
